﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Rose.Models;
using Rose.Helper;

namespace Rose.Controllers
{
    
    [HandleError]
    public class AccountController : Controller
    {
        
        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }
        private Database_RoseEntities db = new Database_RoseEntities();
        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }
       
        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            ViewData["PageTitle"] = "登陆首页";
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "提供的用户名或密码不正确。");
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************
        
        public ActionResult Register()
            
        {
            ViewData["PageTitle"] = "新用户注册";
            ViewData["Message"] = "密码最小长度为" + MembershipService.MinPasswordLength;
            

            return View();
        }


        [ChildActionOnly]
        public ActionResult RegisterPart()
        {
            ViewData["PageTitle"] = "新用户注册";
            ViewData["Message"] = "密码最小长度为" + MembershipService.MinPasswordLength;
           
            return View();
        }


        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
          
            bool hasReturnUrl = false;
            if (!string.IsNullOrEmpty(model.ReturnUrl) && model.ReturnUrl.IndexOf("invitorId") > 0)
                hasReturnUrl = true;
            if (model.ConfirmPassword != model.Password)
            {
                ViewData["Error"] = "两次输入的密码不一致，请重新确认";
                if (hasReturnUrl)
                    return Redirect(model.ReturnUrl);
                return View("Register", model);
            }
            if (HttpContext.Session["captcha"]==null || model.Captcha != HttpContext.Session["captcha"].ToString())
            {
                ViewData["Error"] = "验证码不正确，请重新输入";
                if (hasReturnUrl)
                    return Redirect(model.ReturnUrl);
                return View("Register", model);
            }
            MembershipCreateStatus createStatus = new MembershipCreateStatus();
            try
            {
                if (new AccountHelpModel().FullRegisterUserInfo(model))
                {
                    Membership.CreateUser(model.UserName, model.Password, model.UserName,"schoolparty","schoolparty", true, out createStatus);
                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        if (Membership.ValidateUser(model.UserName, model.Password))
                        {
                            ViewData["Message"] = "注册成功";

                            FormsAuthentication.SetAuthCookie(model.UserName, false);
                            //获得积分
                            ViewData["Error"] = "获得5点积分";
                            if (!string.IsNullOrEmpty(model.ReturnUrl) && model.ReturnUrl.IndexOf("invitorId") > 0)
                            {
                                return View("Home", "Index");

                            }
                            if (!string.IsNullOrEmpty(model.ReturnUrl))
                                return Redirect(model.ReturnUrl);
                            else if (!string.IsNullOrEmpty(FormsAuthentication.DefaultUrl))
                                return Redirect(FormsAuthentication.DefaultUrl);
                            else return View("Home", "Index");
                            //返回默认首页;

                        }
                        else
                        {
                            ViewData["Message"] = "请登录";
                            return View("Account", "LogOn");
                        }
                    }
                    else ViewData["Error"] =new  AccountHelpModel().GetRegisterError(createStatus);
                }
            }
            catch (Exception ex)
            {
                ViewData["Error"] = ex.Message;
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            ViewData["Message"] = "密码最小长度为" + MembershipService.MinPasswordLength;
            ViewData["PageTitle"] = "新用户注册";
            if (hasReturnUrl)
                return Redirect(model.ReturnUrl);
            return View("Register", model);
        }
        //注册成功后还需要注册数据库中的资料
       

       

        ////找回密码功能
        public ActionResult ForgotPassword()
        {
            ViewData["PageTitle"] = "找回密码";
            return View(new ForgotPasswordModel());
        }

        [HttpPost]
        public ActionResult ForgotPassword(ForgotPasswordModel model)
        {
            if (!string.IsNullOrEmpty(model.SecretAnswer))
            {
                try
                {
                    string resetPassword = Membership.Provider.ResetPassword(model.UserName, model.SecretAnswer);
                    if (Membership.ValidateUser(model.UserName, resetPassword))
                    {
                        FormsAuthentication.SetAuthCookie(model.UserName, false);
                        return RedirectToAction("ChangePassword", new { resetPassword = resetPassword });
                    }
                }
                catch (Exception ex)
                {
                    ViewData["Message"] = ex.Message;
                    return View(model);
                }

            }
            if (string.IsNullOrEmpty(model.UserName))
            {
                ViewData["Message"] = "账号不能为空";
                return View(model);
            }
            MembershipUser user = Membership.GetUser(model.UserName, false);
            if (user != null)
            {
                model.SecretQuestion = user.PasswordQuestion;

            }
            else
            {
                ViewData["Message"] = "该账号不存在";
            }
            ViewData["PageTitle"] = "找回密码";
            return View(model);

        }
        // **************************************
        // URL: /Account/ChangePassword
        // **************************************


        [Authorize]
        public ActionResult ChangePassword(string resetPassword)
        {
            ViewData["Message"] = "密码最小长度为" + MembershipService.MinPasswordLength;
            if (string.IsNullOrEmpty(resetPassword))
            {
                return View(new ChangePasswordModel());
            }
            ChangePasswordModel model = new ChangePasswordModel()
            {
                OldPassword = resetPassword
            };
            return View(model);
        }


        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            ViewData["Message"] = "密码最小长度为" + MembershipService.MinPasswordLength;
            if (model.NewPassword != model.ConfirmPassword)
            {
                ViewData["Message"] = "两次输入的密码不一致";
                model.NewPassword = string.Empty;
                model.ConfirmPassword = string.Empty;
                return View(model);
            }
            try
            {
                MembershipUser user = Membership.GetUser(HttpContext.User.Identity.Name, false);
                if (user.ChangePassword(model.OldPassword, model.NewPassword))
                {
                    ViewData["Message"] = "密码更改成功";
                  

                }
                else ViewData["Message"] = "密码更改错误,请重新输入";

                return View(new ChangePasswordModel());//将所有数据清空

            }
            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            catch (Exception ex)
            {
                ViewData["Message"] = ex.Message;
                return View(new ChangePasswordModel());
            }
            
        }
        [Authorize]
        public ActionResult ChangeSecret()
        {

            ViewData["PageTitle"] = "修改保密问题";
            ChangeSecretModel model = new ChangeSecretModel();
            MembershipUser user = Membership.GetUser(HttpContext.User.Identity.Name, false);
            if (user != null)
            {
                model.OldQuestion = user.PasswordQuestion;
                if (model.OldQuestion == "schoolparty")
                    model.OldQuestion = "";

            }
            return View(model);
        }
        [Authorize]
        [HttpPost]
        public ActionResult ChangeSecret(ChangeSecretModel model)
        {
            if (string.IsNullOrEmpty(model.Password) || string.IsNullOrEmpty(model.SecretAnswer) || string.IsNullOrEmpty(model.SecretQuestion))
            {
                ViewData["Message"] = "不能有空项";
                return View(model);
            }
            if (model.SecretQuestion == "schoolparty" || model.SecretAnswer=="schoolparty")
            {
                ViewData["Message"] = "保密问题或答案不能包含网站名";
                return View(model);
            }
            if (string.IsNullOrEmpty(model.OldQuestion))
            {
                model.OldQuestion = "schoolparty";
            }
            try
            {
                MembershipUser user = Membership.GetUser(HttpContext.User.Identity.Name, false);
                if (user != null)
                {
                    if (user.ChangePasswordQuestionAndAnswer(model.Password, model.SecretQuestion, model.SecretAnswer))
                    {
                        ViewData["Message"] = "保密问题修改成功";
                        model.OldQuestion = model.SecretQuestion;
                        model.SecretQuestion = string.Empty;
                        model.SecretAnswer = string.Empty;
                    }
                    else
                    {
                        ViewData["Message"] = "修改失败！";
                       
                    }
                }
            }
            catch (Exception e)
            { ViewData["Message"] = e.Message; }
            return View(model);
        }
        
        public CaptchaResult GetCaptcha(string random)
        {
            string captchaText = Captcha.GenerateRandomCode();
            HttpContext.Session.Add("captcha", captchaText);
            return new CaptchaResult(captchaText);
        }

        [Authorize]
        
        public ActionResult ManageUserInfo()
        {
            ViewData["PageTitle"] = "个人资料";
            UserInfo userInfo=db.UserInfos.Where(p=>p.Id==HttpContext.User.Identity.Name).FirstOrDefault();
            UserInfoModel returnModel = new UserInfoModel()
            {
                Gender = (userInfo.IsMan) ? ("M") : ("F"),

                University = userInfo.University,
                Major = userInfo.Major,
                SchoolYear = userInfo.SchoolYear,
                UserName = HttpContext.User.Identity.Name,

                ////分割
                Email=userInfo.Email??string.Empty,
                College=userInfo.College??string.Empty,
                AddressProvince = userInfo.AddressProvince??string.Empty,
                AddressCity = userInfo.AddressCity??string.Empty,
                AddressTown=userInfo.AddressTown??string.Empty,
                AddressStreet=userInfo.AddressStreet??string.Empty,

                BirthYear = userInfo.BirthDate == null ? DateTime.Now.Year - 19 : userInfo.BirthDate.Value.Year,
                BirthMonth = userInfo.BirthDate == null ? 1 : userInfo.BirthDate.Value.Month,
                BirthDate = userInfo.BirthDate == null ? 1 : userInfo.BirthDate.Value.Day,
                ImagePath = userInfo.ImagePath ?? "/Content/Images/default.png",
                QQ = userInfo.QQ ?? string.Empty,
                WebSite = userInfo.WebSite ?? string.Empty,
                Phone = userInfo.Phone ?? string.Empty,
                ClassRoom = userInfo.ClassRoom ?? string.Empty,
                TrueName = userInfo.Name ?? string.Empty,
                SchoolId = userInfo.SchoolId ?? string.Empty
                
            };
          
            

            ViewData["Gender"] =new  ListHelpModel().GetGenderList(returnModel.Gender);
            ViewData["SchoolYear"] =new  ListHelpModel().GetYearList(returnModel.SchoolYear);

          
            return View(returnModel);
        }
        [Authorize]
        [HttpPost]
        public ActionResult ManageUserInfo(UserInfoModel userInfo)
        {
            
            ViewData["PageTitle"] = "个人资料";
            ViewData["Message"] = "成功保存";
            UserInfo saveModel = db.UserInfos.Where(p => p.Id == HttpContext.User.Identity.Name).FirstOrDefault();
           
                    
            saveModel.IsMan=(userInfo.Gender=="M"||userInfo.Gender=="m")?(true):(false);
           
            
            saveModel.SchoolYear = userInfo.SchoolYear;

            try
            {
                if (userInfo.BirthDate != 0 && userInfo.BirthMonth != 0 && userInfo.BirthYear != 0)
                {
                    saveModel.BirthDate = new DateTime(userInfo.BirthYear, userInfo.BirthMonth, userInfo.BirthDate);

                }

                if ((userInfo.AddressProvince) != null)
                {
                    saveModel.AddressProvince = CheckDataHelpModel.CheckLength(new CheckHelpModel().CheckCity(int.Parse(userInfo.AddressProvince)));

                }
               

                if ((userInfo.AddressCity) != null)
                {
                    saveModel.AddressCity = CheckDataHelpModel.CheckLength(new CheckHelpModel().CheckCity(int.Parse(userInfo.AddressCity)));
                    //userInfo.AddressCity = saveModel.AddressCity;
                }
              

                if ((userInfo.AddressTown) != null)
                {
                    saveModel.AddressTown = CheckDataHelpModel.CheckLength(new CheckHelpModel().CheckCity(int.Parse(userInfo.AddressTown)));
                    //userInfo.AddressTown = saveModel.AddressTown;
                }
              

                if ((userInfo.AddressStreet) != null)
                {
                    saveModel.AddressStreet = CheckDataHelpModel.CheckLength(new CheckHelpModel().CheckCity(int.Parse(userInfo.AddressStreet)));
                    //userInfo.AddressStreet = saveModel.AddressStreet;
                }
                else { saveModel.AddressStreet = string.Empty; }


                if ((userInfo.College) != null)
                {
                    if (int.Parse(userInfo.College) >= 0)
                        saveModel.College = CheckDataHelpModel.CheckLength(new CheckHelpModel().CheckCollege(int.Parse(userInfo.College)));
                    else
                    {
                        saveModel.College = CheckDataHelpModel.CheckLength(userInfo.OtherCollege);
                        College newcollege=db.Colleges.Where(c=>c.Name==saveModel.College).FirstOrDefault();
                        if (newcollege != null)
                        {
                            School_Colleges relation = new School_Colleges()
                            {
                                School = int.Parse(userInfo.University),
                                College = newcollege.CollegeId
                            };
                            db.AddToSchool_Colleges(relation);
                        }
                        else
                        {
                            College col = new College()
                            {
                                Name = saveModel.College,
                                CollegeId = (db.Colleges.Max(c => c.CollegeId) + 1)
                            };
                            db.AddToColleges(col);

                            int newid = col.CollegeId;
                            School_Colleges rel = new School_Colleges()
                            {
                                School = db.Universities.Where(c=>c.Name==userInfo.University).First().UniversityId,
                                College = newid,
                                Id = (db.School_Colleges.Max(c => c.Id) + 1)
                            };
                            db.AddToSchool_Colleges(rel);

                        }


                    }
                    //userInfo.College = saveModel.College;
                }


                if ((userInfo.University) != null)
                {
                    saveModel.University = (CheckDataHelpModel.CheckLength(CheckDataHelpModel.CheckLength(userInfo.University, 32)));
                }

               
            }
            catch { throw new ArgumentException(); }

            saveModel.Major = CheckDataHelpModel.CheckLength(userInfo.Major, 20);

            saveModel.Email = CheckDataHelpModel.CheckLength(userInfo.Email, 50);
            saveModel.ImagePath = CheckDataHelpModel.CheckLength(userInfo.ImagePath,255);
            saveModel.QQ = CheckDataHelpModel.CheckLength(userInfo.QQ,12);
            saveModel.WebSite = CheckDataHelpModel.CheckLength(userInfo.WebSite,100);
            saveModel.Phone = CheckDataHelpModel.CheckLength(userInfo.Phone);
            
            saveModel.Name = CheckDataHelpModel.CheckLength(userInfo.TrueName);
            saveModel.SchoolId = CheckDataHelpModel.CheckLength(userInfo.SchoolId,15);
            //一大撮信息保存

         
            ViewData["Gender"] =new  ListHelpModel().GetGenderList(userInfo.Gender);
            ViewData["SchoolYear"] =new  ListHelpModel().GetYearList(userInfo.SchoolYear);

            db.SaveChanges();

            return Redirect("/Account/ManageUserInfo");
        }
      

    }
}
